package com.seio.edc.util;





import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	/**
	 * 添加cookie
	 * @author gxp  2012-4-25 上午9:32:07 
	 * @param res  HttpServletResponse
	 * @param name  cookie名称
	 * @param value  cookie值
	 */
	public static void addCookie(HttpServletResponse res,String name,String value){
		addCookie( res,name,value,null,-1,null);
	}
	/**
	 * 添加cookie
	 * @author gxp  2012-4-25 上午9:32:07 
	 * @param res  HttpServletResponse
	 * @param name  cookie名称
	 * @param value  cookie值
	 * @param path  路径
	 */
	public static void addCookie(HttpServletResponse res,String name,String value,String path){
		addCookie( res,name,value,path,-1,null);
	}
	/**
	 * 添加cookie
	 * @author gxp  2012-4-25 上午9:32:07 
	 * @param res  HttpServletResponse
	 * @param name  cookie名称
	 * @param value  cookie值
	 * @param path  路径
	 * @param maxage 最大失效时间(秒)
	 */
	public static void addCookie(HttpServletResponse res,String name,String value,String path,int maxage){
		addCookie( res,name,value,path,maxage,null);
	}

	/**
	 * 添加cookie
	 * @author gxp  2012-4-25 上午9:32:07 
	 * @param res  HttpServletResponse
	 * @param name  cookie名称
	 * @param value  cookie值
	 * @param path  路径
	 * @param maxage 最大失效时间(秒)
	 * @param domain  域名
	 */
	public static void addCookie(HttpServletResponse res,String name,String value,String path,int maxage,String domain){
		Cookie cookie = new Cookie(name, value);
		if(path!=null && path.length()>0){
			cookie.setPath(path);
		}
		if(domain!=null && domain.length()>0){
			cookie.setDomain(domain);
		}
		if(maxage>=0){
			cookie.setMaxAge(maxage);
		}
		res.addCookie(cookie);

	}
	/**
	 * 获取cookie
	 * @author gxp  2012-4-25 上午10:05:03 
	 * @param req
	 * @param name
	 * @return
	 */
	public static String getCookie( HttpServletRequest req,String name){
		String returnValue = null;
		Cookie[] cookies = req.getCookies();
		Cookie cookie = null;
		if(cookies!=null && cookies.length>0){
			for (int i = 0; i < cookies.length; i++) {
				cookie = cookies[i];
				if (name.equalsIgnoreCase(cookie.getName().trim())) {
					returnValue = cookie.getValue();
					break;
				}
			}
		}
		return returnValue;
	}
	/**
	 * 删除cookie
	 * @author gxp  2012-4-25 上午9:56:00 
	 * @param res  HttpServletResponse
	 * @param name  cookie名称
	 * @param value  cookie值
	 * @param path  路径
	 */
	public static void deleteCookie(HttpServletResponse res,String name,String path){
		addCookie( res, name,null,path,0,null);
	}
	/**
	 * 删除cookie
	 * @author gxp  2012-4-25 上午9:56:00 
	 * @param res  HttpServletResponse
	 * @param name  cookie名称
	 * @param value  cookie值
	 * @param path  路径
	 * @param domain  域名
	 */
	public static void deleteCookie(HttpServletResponse res,String name,String path,String domain){
		addCookie( res, name,null,path,0,domain);
	}

}
